import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setToken, getToken, removeToken } from '@/common/utils/cache/cookies'
import { getCurrentUserApi } from '@/common/apis/users'
import { routerConfig } from '@/router/config'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(getToken() || '')
  const roles = ref<string[]>([])
  const username = ref<string>('')

  // 设置token
  const ISetToken = (value: string) => {
    setToken(value)
    token.value = value
    console.log(value)
  }

  // 重置token
  const resetToken = () => {
    removeToken()
    token.value = ''
    roles.value = []
  }

  // 异步获取用户详情
  const getInfo = async () => {
    const { data } = await getCurrentUserApi()
    console.log(data)

    roles.value = data.roles
    username.value = data.username
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value =
      data.roles?.length > 0 ? data.roles : routerConfig.defaultRoles
  }

  // 登出
  const logout = () => {
    removeToken()
    token.value = ''
    roles.value = []
    // resetRouter()
    // resetTagsView()
  }

  return { token, roles, username, ISetToken, logout, getInfo, resetToken }
})
